package it.xiuxian.lib

import android.app.Activity
import android.content.ContentValues.TAG
import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.annotation.MainThread
import androidx.databinding.DataBindingUtil
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bytedance.sdk.openadsdk.*
import com.bytedance.sdk.openadsdk.TTAdNative.SplashAdListener
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.HttpHeaders
import io.reactivex.disposables.Disposable
import it.xiuxian.lib.base.App
import it.xiuxian.lib.base.ArouterAddress
import it.xiuxian.lib.databinding.ActivityLibBinding
import it.xiuxian.lib.http.SPConfig
import it.xiuxian.lib.utils.*
import kotlinx.android.synthetic.main.activity_lib.*
import java.lang.ref.SoftReference
import java.lang.ref.WeakReference


@Route(path = ArouterAddress.LibAcitivity)
class LibAcitivity: Activity(){
    var heads: HttpHeaders?=null
    private val TAG = "LibAcitivity1"
    private var disposable: Disposable? = null
    var token:String?=null
    var binding:ActivityLibBinding?=null
    override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        NavigationBarStatusBar(this, true)
       // setContentView(R.layout.activity_lib)
       // ImageUtil.setOriginImage(R.mipmap.app_qidong, iv)
      binding =  DataBindingUtil.setContentView<ActivityLibBinding>(this,R.layout.activity_lib)
       /* if (!isTaskRoot()) {
            finish()
            return
        }*/
        token = SPUtil.get(SPConfig.SESSION_ID, "")
        Log.e("mytoken",token!!)
        /* OkGo.<HttpData<List<AreaCodeEnum>>>post(BaseHttpConfig.BASE_URL + "/app/user/getAreaCode")
                .execute(new JsonCallBack<HttpData<List<AreaCodeEnum>>>() {
                    @Override
                    public void onSuccess(Response<HttpData<List<AreaCodeEnum>>> response) {
                        HttpData<List<AreaCodeEnum>> httpData = response.body();

                        SPUtil.putBean(SPConfig.AREA_CODE_LIST, (ArrayList) httpData.getData());
                    }
                });*//*disposable =
            Flowable.timer(1000, TimeUnit.MILLISECONDS).compose(RxSchedulersHelper.transformer())
                .subscribe(
                        Consumer {
                            if (isflag == "0") {
                                SPUtil.put(SPConfig.ISFIRST, "1")
                                ARouter.getInstance().build(ArouterAddress.FIRSTACTIVITY).navigation()
                            } else {*/
        //step2:创建TTAdNative对象
                        mTTAdNative = TTAdManagerHolder.get().createAdNative(this)
                            getExtraInfo()
                            loadSplashAd()

                          /*  }

                            finish()
                        }
                )*/

    }
    private fun getExtraInfo(){
        val intent = intent ?: return
        val codeId = intent.getStringExtra("splash_rit")
        if (!TextUtils.isEmpty(codeId)) {
            mCodeId = codeId!!
        }
        mIsExpress = intent.getBooleanExtra("is_express", false)
        mIsHalfSize = intent.getBooleanExtra("is_half_size", false)
        mIsSplashClickEye = intent.getBooleanExtra("is_splash_click_eye", false)
    }
    /**
     * 导航栏，状态栏隐藏
     * @param activity
     */
    fun NavigationBarStatusBar(activity: Activity, hasFocus: Boolean){
        if (hasFocus && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            val decorView = activity.window.decorView
            decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        }
    }
    private val AD_TIME_OUT = 3000
    private var mCodeId = "887669101"
    private var mIsExpress = false //是否请求模板广告

    private var mIsHalfSize = false //是否是半全屏开屏
    private var mTTAdNative: TTAdNative? = null
    private var mSplashContainer: FrameLayout? = null
    private var mIsSplashClickEye = false //是否是开屏点睛
    private var mSplashAd: TTSplashAd? = null
    private var mSplashHalfSizeLayout: LinearLayout? = null
    private var mSplashSplashContainer: FrameLayout? = null

    /**
     * 加载开屏广告
     */
    private fun loadSplashAd() {
        mSplashContainer = binding!!.splashContainer
        mSplashHalfSizeLayout = binding!!.splashHalfSizeLayout
        mSplashSplashContainer = binding!!.splashContainerHalfSize
        SplashClickEyeManager(this).setSupportSplashClickEye(false)
        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
        val dm = DisplayMetrics()
        windowManager.defaultDisplay.getRealMetrics(dm)
        val splashWidthDp: Float = UIUtils.getScreenWidthDp(this)
        val splashWidthPx: Int = UIUtils.getScreenWidthInPx(this)
        val screenHeightPx: Int = UIUtils.getScreenHeight(this)
        val screenHeightDp: Float = UIUtils.px2dip(this, screenHeightPx.toFloat()).toFloat()
        val splashHeightDp: Float
        val splashHeightPx: Int
        if (mIsHalfSize) {
            // 开屏高度 = 屏幕高度 - 下方预留的高度，demo中是预留了屏幕高度的1/5，因此开屏高度传入 屏幕高度*4/5
            splashHeightDp = screenHeightDp * 4 / 5f
            splashHeightPx = (screenHeightPx * 4 / 5f).toInt()
        } else {
            splashHeightDp = screenHeightDp
            splashHeightPx = screenHeightPx
        }
        val adSlot = AdSlot.Builder()
            .setCodeId(mCodeId) //模板广告需要设置期望个性化模板广告的大小,单位dp,代码位是否属于个性化模板广告，请在穿山甲平台查看
            //view宽高等于图片的宽高
            .setExpressViewAcceptedSize(splashWidthDp, splashHeightDp) // 单位是dp
            .setImageAcceptedSize(splashWidthPx, splashHeightPx) // 单位是px
            .build()

        //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理
        val listener: TTSplashAd.AdInteractionListener =
            SplashAdInteractionListener(
                this,
                mIsSplashClickEye,
               binding!!.splashContainer
            )
        mTTAdNative!!.loadSplashAd(adSlot, object : SplashAdListener{
            @MainThread
            override fun onError(code: Int, message: String) {
                Log.d(TAG, message)
                ToastUtil.showShort(message)
                goMain()
            }

            @MainThread
            override fun onTimeout() {
                ToastUtil.showShort("开屏广告加载超时")
                goMain()
            }

            @MainThread
            override fun onSplashAdLoad(ad: TTSplashAd) {
                Log.d(TAG, "开屏广告请求成功")
                if (ad == null) {
                    return
                }
                mSplashAd = ad

                //获取SplashView
                val view = ad.splashView
                //初始化开屏点睛相关数据
                initSplashClickEyeData(mSplashAd, view)
                if (mIsHalfSize) {
                    if (view != null && mSplashSplashContainer != null && !isFinishing()) {
                        mSplashHalfSizeLayout!!.setVisibility(View.VISIBLE)
                        mSplashSplashContainer!!.setVisibility(View.VISIBLE)
                        if (binding!!.splashContainer != null) {
                            binding!!.splashContainer.setVisibility(View.GONE)
                        }
                        mSplashSplashContainer!!.removeAllViews()
                        //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕高
                        mSplashSplashContainer!!.addView(view)
                        /**
                         * 设置是否开启开屏广告倒计时功能以及不显示跳过按钮,如果设置为true，您需要自定义倒计时逻辑，
                         * 参考样例请看：
                         * @see SplashActivity.useCustomCountdownButton
                         */
                        //useCustomCountdownButton(false,ad);
                    } else {
                       goMain()
                    }
                } else {
                    if (view != null && binding!!.splashContainer != null && !isFinishing()) {
                        binding!!.splashContainer.setVisibility(View.VISIBLE)
                        if (mSplashHalfSizeLayout != null) {
                            mSplashHalfSizeLayout!!.setVisibility(View.GONE)
                        }
                        binding!!.splashContainer.removeAllViews()
                        //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕高
                        binding!!.splashContainer.addView(view)
                        /**
                         * 设置是否开启开屏广告倒计时功能以及不显示跳过按钮,如果设置为true，您需要自定义倒计时逻辑，
                         * 参考样例请看：
                         * @see SplashActivity.useCustomCountdownButton
                         */
                        //useCustomCountdownButton(false,ad);
                    } else {
                        goMain()
                    }
                }


                //设置SplashView的交互监听器
                ad.setSplashInteractionListener(listener)
                if (ad.interactionType == TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
                    ad.setDownloadListener(object : TTAppDownloadListener {
                        var hasShow = false
                        override fun onIdle() {}
                        override fun onDownloadActive(
                            totalBytes: Long,
                            currBytes: Long,
                            fileName: String,
                            appName: String
                        ) {
                            if (!hasShow) {
                              //  ToastUtil.showShort("下载中...")
                                hasShow = true
                            }
                        }

                        override fun onDownloadPaused(
                            totalBytes: Long,
                            currBytes: Long,
                            fileName: String,
                            appName: String
                        ) {
                           // ToastUtil.showShort("下载暂停...")
                        }

                        override fun onDownloadFailed(
                            totalBytes: Long,
                            currBytes: Long,
                            fileName: String,
                            appName: String
                        ) {
                           // ToastUtil.showShort("下载失败...")
                        }

                        override fun onDownloadFinished(
                            totalBytes: Long,
                            fileName: String,
                            appName: String
                        ) {
                           // ToastUtil.showShort("下载完成...")
                        }

                        override fun onInstalled(fileName: String, appName: String) {
                          //  ToastUtil.showShort("安装完成...")
                        }
                    })
                }
            }
        }, AD_TIME_OUT)
    }
    fun goMain(){
        if (TextUtils.isEmpty(token)) {
            ARouter.getInstance().build(ArouterAddress.LOGINACTIVITY)
                .navigation()
            finish()
        } else {
            if (OkGo.getInstance().commonHeaders != null) {
                heads = OkGo.getInstance().commonHeaders
            } else {
                heads = OkGo.getInstance()
                    .addCommonHeaders(OkGo.getInstance().commonHeaders).commonHeaders
            }
            heads!!.put(SPConfig.SESSION_ID, token)
            // ARouter.getInstance().build(ArouterAddress.FOURACTIVITY).navigation()
            ARouter.getInstance().build(ArouterAddress.MAINACTIVITY).withString(
                "sessionId",
                token
            ).navigation()
            finish()
        }
    }
    private var mSplashClickEyeManager:SplashClickEyeManager? = null
    private var mSplashClickEyeListener: SplashClickEyeListener? = null
    private fun initSplashClickEyeData(splashAd: TTSplashAd?, splashView: View?) {
        if (splashAd == null || splashView == null) {
            return
        }
        mSplashClickEyeListener = SplashClickEyeListener(
            this,
            splashAd,
            binding!!.splashContainer,
            mIsSplashClickEye
        )
        splashAd.setSplashClickEyeListener(mSplashClickEyeListener)
        mSplashClickEyeManager = SplashClickEyeManager(this)
        mSplashClickEyeManager!!.setSplashInfo(splashAd, splashView, window.decorView)
    }
    class SplashAdInteractionListener(
        activity: Activity?,
        isSplashClickEye: Boolean,
        splashContainer: ViewGroup
    ) :
        TTSplashAd.AdInteractionListener {
        var mContextRef: WeakReference<Activity?>
        private val mIsSplashClickEye: Boolean
        private val mSplashContainer: ViewGroup
        var token:String?=null
        var heads: HttpHeaders?=null
        override fun onAdClicked(view: View, type: Int) {
            Log.d(TAG, "onAdClicked")
          //  ToastUtil.showShort("开屏广告点击")
        }

        override fun onAdShow(view: View, type: Int) {
            Log.d(TAG, "onAdShow")
          //  ToastUtil.showShort("开屏广告展示")
        }

        override fun onAdSkip() {
            Log.d(TAG, "onAdSkip")
          //  ToastUtil.showShort("开屏广告跳过")
            goToMainActivity(mIsSplashClickEye, mSplashContainer)
        }

        override fun onAdTimeOver() {
            Log.d(TAG, "onAdTimeOver")
          //  ToastUtil.showShort("开屏广告倒计时结束")
            goToMainActivity(mIsSplashClickEye, mSplashContainer)
        }

        private fun ToastUtil.showShort(context: Context?, msg: String) {
            if (context == null || TextUtils.isEmpty(msg)) {
                return
            }
           // TToast.show(context, msg)
        }

        private fun goToMainActivity(isSplashClickEye: Boolean, splashContainer: ViewGroup?) {
            token = SPUtil.get(SPConfig.SESSION_ID, "")
            if (mContextRef.get() == null){
                return
            }
            val isSupport = SplashClickEyeManager(App.INSTANCE).isSupportSplashClickEye
            if (isSplashClickEye){
                if (isSupport){
                    return
                } else {
                   // ToastUtil.showShort("物料不支持点睛，直接返回到主界面")
                    SplashClickEyeManager(App.INSTANCE).clearSplashStaticData()
                }
            }
            if (TextUtils.isEmpty(token)) {
                ARouter.getInstance().build(ArouterAddress.LOGINACTIVITY)
                    .navigation()
            } else {
                if (OkGo.getInstance().commonHeaders != null) {
                    heads = OkGo.getInstance().commonHeaders
                } else {
                    heads = OkGo.getInstance()
                        .addCommonHeaders(OkGo.getInstance().commonHeaders).commonHeaders
                }
                heads!!.put(SPConfig.SESSION_ID, token)
                // ARouter.getInstance().build(ArouterAddress.FOURACTIVITY).navigation()
                ARouter.getInstance().build(ArouterAddress.MAINACTIVITY).withString(
                    "sessionId",
                    token
                ).navigation()
            }
            splashContainer?.removeAllViews()
            mContextRef.get()!!.finish()
        }

        init {
            mContextRef = WeakReference(activity)
            mIsSplashClickEye = isSplashClickEye
            mSplashContainer = splashContainer
        }
    }
    class SplashClickEyeListener(
        activity: Activity?,
        splashAd: TTSplashAd?,
        splashContainer: View?,
        isFromSplashClickEye: Boolean
    ) : ISplashClickEyeListener {
        private val mActivity: SoftReference<Activity?>
        private val mSplashAd: TTSplashAd?
        private val mSplashContainer: View?
        private var mIsFromSplashClickEye = false
        override fun onSplashClickEyeAnimationStart() {
            //开始执行开屏点睛动画
            if (mIsFromSplashClickEye) {
                startSplashAnimationStart()
            }
        }

        override fun onSplashClickEyeAnimationFinish() {
            //sdk关闭了了点睛悬浮窗
            val splashClickEyeManager = SplashClickEyeManager(App.INSTANCE)
            val isSupport = splashClickEyeManager.isSupportSplashClickEye
            if (mIsFromSplashClickEye && isSupport) {
                finishActivity()
            }
            splashClickEyeManager.clearSplashStaticData()
        }

        override fun isSupportSplashClickEye(isSupport: Boolean): Boolean {
            val splashClickEyeManager = SplashClickEyeManager(App.INSTANCE)
            splashClickEyeManager.isSupportSplashClickEye = isSupport
            return false
        }

        private fun finishActivity() {
            if (mActivity.get() == null) {
                return
            }
            mActivity.get()!!.finish()
        }

        private fun startSplashAnimationStart() {
            if (mActivity.get() == null || mSplashAd == null || mSplashContainer == null) {
                return
            }
            val splashClickEyeManager = SplashClickEyeManager(App.INSTANCE)
            val content = mActivity.get()!!.findViewById<ViewGroup>(android.R.id.content)
            splashClickEyeManager.startSplashClickEyeAnimation(
                mSplashContainer,
                content,
                content,
                object : SplashClickEyeManager.AnimationCallBack{
                    override fun animationStart(animationTime: Int) {}
                    override fun animationEnd() {
                        if (mSplashAd != null) {
                            mSplashAd.splashClickEyeAnimationFinish()
                        }
                    }
                })
        }

        init {
            mActivity = SoftReference(activity)
            mSplashAd = splashAd
            mSplashContainer = splashContainer
            mIsFromSplashClickEye = isFromSplashClickEye
        }

    }

    /*override fun onRestart() {
        super.onRestart()
        goMain()

    }*/
}